package util

import org.openscience.cdk.DefaultChemObjectBuilder
import org.openscience.cdk.inchi.InChIToStructure
import org.openscience.cdk.interfaces.IAtomContainer
import org.openscience.cdk.interfaces.IMolecularFormula
import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator
import org.openscience.cdk.smiles.SmilesGenerator
import org.openscience.cdk.AtomContainer
import org.openscience.cdk.Molecule
import net.sf.jniinchi.JniInchiOutputKey
import net.sf.jniinchi.JniInchiWrapper
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.InchFinder
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.SdfToInchi

/**
 * Created by IntelliJ IDEA.
 * User: wohlgemuth
 * Date: Mar 10, 2010
 * Time: 4:09:46 PM
 */
class ConvertInchi {

    /**
     * converts an inchi code to a molare mass
     * @param inchi
     * @return
     */
    public static double convertInchiToMolareMass(String inchi) {

        IMolecularFormula moleculeFormula = MolecularFormulaManipulator.getMolecularFormula(convertInchiToMolecularFormula(inchi), DefaultChemObjectBuilder.getInstance())

        return MolecularFormulaManipulator.getTotalExactMass(moleculeFormula)

    }

    /**
     *
     * converts an inchi to a molecular formula
     * @param
     inchi
     * @return
     */
    public static String convertInchiToMolecularFormula(String inchi) {
        return inchi.split("/")[1]

    }

    public static String convertInchiToKey(String inchi) {
        JniInchiOutputKey inchiKey = JniInchiWrapper.getInChIKey(inchi);
        return inchiKey.getKey()
    }

    /**
     * converts an inchi code to a molecule
     * @param
     inchi
     * @return
     */
    public static IAtomContainer convertInChIToMolecule(String inchi) {

        InChIToStructure convert = new InChIToStructure(inchi, DefaultChemObjectBuilder.getInstance())
        IAtomContainer container = convert.getAtomContainer()

        return container
    }


    public static String convertAtomContainerToSmile(IAtomContainer container) {
        SmilesGenerator sg = new SmilesGenerator();

        return sg.createSMILES(new Molecule(container))
    }

    public static String convertMolToInchi(String molFile){
                 SDFFinder finder = new SDFFinder()

        SdfToInchi.sdfToInchi(new ByteArrayInputStream(molFile.trim().getBytes()), finder)

        return finder.inchi
    }
}

class SDFFinder implements InchFinder {

    Logger log = Logger.getLogger(getClass())
    String inchi = ""

    void foundInchi(String s, Map<Object, Object> objectObjectMap) {
        log.debug "found inchi: ${s}"
        inchi = s;
    }


}